import { getRouters } from '@/api/userManagement/menu'
import store from '@/store'

/**
 * Filter asynchronous routing tables by recursion
 * @param routes
 * @param roles
 * parentId: 0,//菜单栏父id
  menuId: 1,//菜单栏id
  menuName: '系统管理',//菜单栏名称,
  path: '/systemManagement',//菜单栏路径
  component: '/blankLayout',//组件
  redirect: '',//是否打开外连接
  visible: 1,//菜单栏是否隐藏 0或者1
  orderNum: 1,//显示排序
  menuType: "m",//菜单栏类型 M:目录 C:菜单
  target: "",//当前窗口:""新窗口:_blank  menuType:C显示
  icon: 's-data',//icon menuType:C显示
 */

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = routes
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      getRouters({ mgrSn: store.getters.mgrSn }).then(res => {
        var routesList = [
          {
            path: '/',
            component: () => import('@/layout'),
            redirect: '/userManagement/userList',
            children: [],
          },
        ]
        filterAsyncRoutes(res.data.resultData, routesList[0].children, 0)
        commit('SET_ROUTES', routesList)
        resolve(routesList)
      })
    })
  }
}

const loadView = (view) => { // 路由懒加载
  return resolve => require([`@/views/${view}`], resolve)
}

function filterAsyncRoutes(list, arr, parentId) {
  list.forEach(item => {
    if (item && item.parentId === parentId) {
      console.log(item.visible)
      var child = {
        path: item.path && item.path.length > 0 ? item.path : undefined,
        name: item.menuKey,
        component: loadView(item.component || 'blankLayout'),
        meta: {
          title: item.menuName,
          icon: item.icon || undefined,
          target: item.target
        },
        children: []
      }
      item.redirect && (child.redirect = item.redirect)
      if (item.visible) {
        child.hidden = true
      }
      filterAsyncRoutes(list, child.children, item.menuId)
      arr.push(child)
    }
  })
}




export default {
  namespaced: true,
  state,
  mutations,
  actions
}
